/*
 * @Description: 原文检测 - 安全性检测
 * @Author: Rfan
 * @Date: 2022-10-10 14:19:09
 * @LastEditTime: 2022-10-21 18:11:49
 */

import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Checkbox, Space } from 'antd';
import cs from 'classnames';
import classnames from 'classnames/bind';
import { editItemById, insertItem, selectItemByKey } from '@/utils/list';
import { CheckProps, EnumSecurityRuleType } from '../../../../../../dictionaries';
import type { IPropsRule } from '../../../../../../interface';
import styles from '../../../styles/main.module.scss';
import { isNullObj } from '@/utils';
import { useAddPlanDialogContext } from '@/view/system/ArchivesDetection/components/dialogs/AddPlan/contexts/AddPlanDialogContext';

const cx = classnames.bind(styles);

// 条目可用性规则列表类型
type TRuleList = IPropsRule<EnumSecurityRuleType>[];

// 条目可用性完整类型
interface ISecurityFullRules {
  ruleType: CheckProps.Security;
  rules: TRuleList;
}

const OriginalSecurityCheck = (props: any, ref: any) => {
  const { currentRuleInfo, getPropertyRules } = useAddPlanDialogContext();

  // 规则列表
  const [ruleList, setRuleList] = useState<TRuleList>([]);

  useImperativeHandle(ref, () => ({
    save: () => {
      const fullRules: ISecurityFullRules = {
        ruleType: CheckProps.Security,
        rules: ruleList
      };
      return fullRules;
    }
  }));

  /**
   * @description: 获取到规则后回写
   */
  useEffect(() => {
    if (currentRuleInfo && !isNullObj(currentRuleInfo)) {
      const ruleObj = getPropertyRules(CheckProps.Security);
      setRuleList(ruleObj?.rules || []);
    }
  }, [currentRuleInfo]);

  /**
   * @description: 获取规则选中状态
   * @param {EnumSecurityRuleType} type 真实性检测类型
   * @return {boolean} 选中状态
   */
  const getRuleState = (type: EnumSecurityRuleType): boolean => {
    const currentRule = selectItemByKey(type, ruleList, 'ruleType');
    return currentRule?.ruleValid;
  };

  /**
   * @description: 设置规则选中状态
   * @param {boolean} valid 选中状态
   * @param {EnumSecurityRuleType} type 真实性检测类型
   */
  const setRuleState = (valid: boolean, type: EnumSecurityRuleType) => {
    const currentRule = selectItemByKey(type, ruleList, 'ruleType');
    const editRule = currentRule
      ? editItemById(type, { ...currentRule, ruleValid: valid }, ruleList, 'ruleType')
      : insertItem({ ruleType: type, ruleValid: valid }, ruleList);
    setRuleList(editRule);
  };

  return (
    <div className={cs(cx('property-wrap'))}>
      <Space className={cx('property--title-wrap')} align="center">
        <h6 className={cx('property--title')}>原文安全性检测</h6>
      </Space>
      <Checkbox
        checked={getRuleState(EnumSecurityRuleType.OriginalVirusInfection)}
        onChange={(evt) => {
          setRuleState(evt.target.checked, EnumSecurityRuleType.OriginalVirusInfection);
        }}
      >
        病毒感染检测
      </Checkbox>
    </div>
  );
};

export default forwardRef(OriginalSecurityCheck);
